/*
Copyright (c) 2012 the VATSIM Connector project

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#ifndef __XPINN__XPINN_H__
#define __XPINN__XPINN_H__

#include <vector>
#include <string>
#include <utility>
#include <XPLMDefs.h>
#include <set>

namespace xpsdk
{
  /**
   * An integer type that is big enough to store a pointer. This type differs
   * according to the SDK version. Prior to 2.1, `long` was used. When 64-bit
   * was introduced in 2.1, this was replaced with `intptr_t`.
   */
#if defined(kXPLM_Version) && kXPLM_Version < 210
  typedef long intptr;
#else
  typedef intptr_t intptr;
#endif
}

/**
 * Used internally to export classes from shared libraries, for testing.
 */
#if defined(NDEBUG)
# define DEBUG_EXPORT
#elif defined(ENABLE_DEBUG_EXPORTS)
# if __GNUC__ >= 4
#   define DEBUG_EXPORT __attribute__((visibility("default")))
# elif IBM || (APL && ! __MACH__)
#   define DEBUG_EXPORT __declspec(dllexport)
# endif
#else
# if IBM || (APL && ! __MACH__)
#   define DEBUG_EXPORT __declspec(dllimport)
# else
#   define DEBUG_EXPORT
# endif
#endif

/**
 * Ratio of a circle's circumference to its diameter.
 */
#define XPINN_PI (3.14159265359)

/**
 * Convert feet to meters.
 */
template <typename T>
T xpinnFeetToMeters(T in) { return in * 0.3048; }

/**
 * Convert meters to feet.
 */
template <typename T>
T xpinnMetersToFeet(T in) { return in / 0.3048; }

/**
 * Convert degrees to radians.
 */
template <typename T>
T xpinnDegToRad(T in) { return in * XPINN_PI / 180; }

/**
 * Convert radians to degrees.
 */
template <typename T>
T xpinnRadToDeg(T in) { return in * 180 / XPINN_PI; }

/**
 * Calculate great circle distance in nautical miles between two lat/lon
 * positions in degrees.
 */
template <typename T>
T xpinnGreatCircleDistance(T lat1, T lon1, T lat2, T lon2)
{
  static T const earthRadius = 3440;
  T dLat = xpinnDegToRad(lat2 - lat1);
  T dLon = xpinnDegToRad(lon2 - lon1);

  T a = std::pow(std::sin(dLat/2), 2) + std::pow(std::sin(dLon/2), 2)
	* std::cos(xpinnDegToRad(lat1)) * std::cos(xpinnDegToRad(lat2));

  return earthRadius * 2 * std::atan2(std::sqrt(a), std::sqrt(1 - a));
}

/**
 * Split a string into multiple strings by separating on a chosen delimiter.
 *
 * Supports returning the strings in any container type that has an empty and
 * a copy constructor and the methods `push_back()` and `back()`.
 */
template <typename V>
V xpinnSplit(std::string const& str, char delim)
{
  V ret;
  ret.push_back(std::string());
  for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
  {
    if (*it == delim) ret.push_back(std::string());
    else ret.back().push_back(*it);
  }
  return ret;
}

/**
 * Returns the X-Plane system root path, with a trailing directory separator.
 *
 * This is a wrapper around XPLMGetSystemPath.
 */
std::string xpinnGetSystemPath();

/**
 * Replaces all forward slashes with the platform native directory separator.
 */
std::string xpinnToPlatformPath(std::string const&);

/**
 * Returns the path for XPInn resources.
 */
std::string xpinnGetResourcePath();

/**
 * Splits a path into its directory and filename components.
 *
 * This is a wrapper around XPLMExtractFileAndPath.
 */
std::pair<std::string, std::string> xpinnSplitPath(std::string const&);

/**
 * Returns the physical paths of all objects in the library which match the
 * provided logical path.
 *
 * This is a wrapper around XPLMLookupObjects.
 */
std::vector<std::string> xpinnLookupObjects(std::string const& path, float lat = 0.0f, float lon = 0.0f);

/**
 * A simple, non-reassignable, non-copiable weak pointer type.
 *
 * The parameter type T must subclass XPInnWeakPtrSubject or provide the same
 * interface as XPInnWeakPtrSubject.
 */
template <class T>
class XPInnWeakPtr
{
public:
  explicit XPInnWeakPtr(T* ptr) : m_ptr(ptr) { if (m_ptr) m_ptr->weakPtrSubscribe(this); }
  ~XPInnWeakPtr() { if (m_ptr) m_ptr->weakPtrUnsubscribe(this); }

  T* get() { return m_ptr; }
  T const* get() const { return m_ptr; }

  void notifyDeleted() { m_ptr = 0; }

private:
  T* m_ptr;

  XPInnWeakPtr(XPInnWeakPtr&);
  XPInnWeakPtr& operator= (XPInnWeakPtr&);
};

/**
 * Classes derived from this class can have pointers tracked by XPInnWeakPtr.
 *
 * Uses the CRTP idiom.
 */
template <class T>
class XPInnWeakPtrSubject
{
protected:
  ~XPInnWeakPtrSubject()
  {
    for (std::set<XPInnWeakPtr<T>*>::iterator it = m_weakPtrs.begin(); it != m_weakPtrs.end(); ++it)
      (*it)->notifyDeleted();
  }
public:
  void weakPtrSubscribe(XPInnWeakPtr<T>* wp) { m_weakPtrs.insert(wp); }
  void weakPtrUnsubscribe(XPInnWeakPtr<T>* wp) { m_weakPtrs.erase(wp); }
private:
  std::set<XPInnWeakPtr<T>*> m_weakPtrs;
};

#endif //__XPINN__XPINN_H__